/**
 *
 *
 * 程序异常处理
 *
 */

const errors = require('../errors');
// const Log = require('../utils/base_util/Log');
module.exports = function (app) {


    //404
    app.use((req, res, next) => {
        next(new errors.NotFoundError(`未找到对应的url:${req.method}:${req.url}`))
    });

    //error handler
    app.use((err, req, res, next) => {
        const env = process.env.NODE_ENV
        const startDate = new Date()
        if (env !== 'test') {
            let error = {
                method: req.method,
                url: req.url,
                statusCode: err.code || 500,
                requestHead: req.headers,
                errorMessage: err.message,
                err: err,
                // position: err.stack.replace(/\s+/g, '')
            }
            if (err.hasOwnProperty('detail')) {
                error.detail = err.detail
            }
            res.on('finish', () => {
                let duration = new Date() - startDate
                error.duration = `${duration}ms`
            })
            // Log.error(err.message, error, true)
            console.log(err.stack)
        }
        res.json({
            code: err.code ? err.code : 500,
            msg: err.message ? err.message : '服务器内部错误',
        })
    })



};
